package com.in.utils;

import com.in.dto.EmailDto;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * @ClassName SendEmailUtil
 * @Description 发送邮件
 * @Author liulianjia
 * @Date 2024/12/3 10:58
 */
@Slf4j
@Service
public class SendEmailUtil {
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private RedisUtil redisUtil;

    @Value("${spring.mail.username}")
    private String myEmail;

    //发送邮件方法
    public boolean sendAuthCode(EmailDto dto) throws MessagingException, UnsupportedEncodingException {

        MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage);

        mimeMessageHelper.setFrom(myEmail, dto.getDisplayName());
        mimeMessageHelper.setTo(dto.getEmailAddress());
        mimeMessageHelper.setSubject(dto.getSubject());
        mimeMessageHelper.setText(dto.getText());

        try {
            javaMailSender.send(mimeMailMessage);
        } catch (MailException e) {
            log.error("{} 邮件发送失败,原因 {}", dto.getEmailAddress(), e.getMessage());
            return false;
        }
        log.info("{} 邮件发送成功", dto.getEmailAddress());
        //设置缓存，过期时间3分钟
        return redisUtil.set(CommonConstant.PREFIX_EMAIL + dto.getEmailAddress(), dto.getCode(), 180);
    }
}
